package com.yunkaweilai.android.activity.login;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.lazylibrary.util.StringUtils;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.web.WebActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.Web;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 注册
 * Created by Administrator on 2017/7/24.
 */

public class RegisterActivity extends BaseActivity {

    @BindView(R.id.id_edt_zh)
    EditText idEdtZh;
    @BindView(R.id.id_edt_pass1)
    EditText idEdtPass1;
    @BindView(R.id.id_edt_phone)
    EditText idEdtPhone;
    @BindView(R.id.id_llayout_hy)
    LinearLayout idLlayoutHy;
    @BindView(R.id.id_checkbox)
    CheckBox idCheckbox;
    @BindView(R.id.id_checkbox2)
    CheckBox idCheckbox2;
    @BindView(R.id.id_btn_next)
    Button idBtnNext;
    @BindView(R.id.id_tv_go_login)
    TextView idTvGoLogin;
    @BindView(R.id.id_tv_industry)
    TextView idTvIndustry;
    @BindView(R.id.id_tv_agreement)
    TextView idTvAgreement;
    @BindView(R.id.id_tv_agreement2)
    TextView idTvAgreement2;
    @BindView(R.id.id_check_pass)
    CheckBox idCheckPass;

    private String industry_code = "";
    private String userName = "";

    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable CheckUser = new Runnable() {
        @Override
        public void run() {
            //在这里调用服务器的接口，获取数据
            checkUserName();
        }
    };

    private boolean ifCheck = true;

    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        idTvAgreement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
        idTvAgreement2.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
        new TitleBuilder(mAc).setTitleText("免费注册")
                .setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
        initClick();
    }

    private void initClick() {
        idCheckPass.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    //如果选中，显示密码
                    idEdtPass1.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //否则隐藏密码
                    idEdtPass1.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                idEdtPass1.setSelection(idEdtPass1.length());
            }
        });

        idEdtZh.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
//                if (CheckUser != null) {
//                    //每次editText有变化的时候，则移除上次发出的延迟线程
//                    handler.removeCallbacks(CheckUser);
//                }
//                userName = s.toString();
//                //延迟800ms，如果不再输入字符，则执行该线程的run方法
//                if (!StringUtils.isEmpty(userName)) {
//                    handler.postDelayed(CheckUser, 1000);
//                }
            }
        });

    }

    @OnClick({R.id.id_btn_next, R.id.id_tv_go_login, R.id.id_llayout_hy, R.id.id_tv_agreement,R.id.id_tv_agreement2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_tv_time:
                if (StringUtils.isEmpty(idEdtZh.getText().toString()) || StringUtils.isEmpty(idEdtPhone.getText().toString())) {
                    showToast("请输入帐号,手机号码");
                } else {
                    if (idEdtPhone.length() == 11) {
                        if (ifCheck) {
                            check();
                        } else {
                            showToast("此账号已被占用，请更换");
                        }
                    } else {
                        showToast("请输入正确手机号码");
                    }
                }
                break;
            case R.id.id_btn_next://注册
                isRight();
                break;
            case R.id.id_tv_go_login:
                finish();
                break;
            case R.id.id_llayout_hy://选择行业
                startActivityForResult(new Intent(mAc, IndustryActivity.class), 601);
                break;
            case R.id.id_tv_agreement://服务协议
                WebActivity.actionStart(mAc, Web.PRIVACY_CLAUSE);
                break;
            case R.id.id_tv_agreement2://用户协议
                WebActivity.actionStart(mAc, Web.YONGHU_CLAUSE);
                break;
        }
    }

    //验证
    private void isRight() {
        if (StringUtils.isEmpty(idEdtZh.getText().toString())) {
            showToast("请输入注册账号");
            return;
        }
        if (idEdtZh.getText().toString().length() < 5 || idEdtZh.getText().toString().length() > 20) {
            showToast("请输入5到20位注册账号");
            return;
        }
        if (StringUtils.isEmpty(idEdtPass1.getText().toString())) {
            showToast("请输入密码");
            return;
        }
        if (StringUtils.isEmpty(idEdtPhone.getText().toString())) {
            showToast("请输入手机号码");
            return;
        } else if (idEdtPhone.length() != 11) {
            showToast("请输入正确手机号码");
            return;
        }
        if (StringUtils.isEmpty(industry_code)) {
            showToast("请选择一个行业");
            return;
        }
        if (!idCheckbox2.isChecked()) {
            showToast("还未同意用户条款协议");
            return;
        }
        if (!idCheckbox.isChecked()) {
            showToast("还未同意隐私条款协议");
            return;
        }
        userName = idEdtZh.getText().toString();
        checkUserName();
//            finish();
    }

    private void check() {
        HttpRequest.postUrl(Api.ACCOUNT_PASSWORD_CHECK)
                .addParams("type", "Register")
                .addParams("UserName", idEdtZh.getText().toString())
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast("获取验证码失败");
                    }
                });
    }

    private void initHttp() {
        HttpRequest.postUrl(Api.REGISTER_URL)
                .addParams("phone", idEdtPhone.getText().toString())
                .addParams("UserName", idEdtZh.getText().toString())
                .addParams("Password", idEdtPass1.getText().toString())
                .addParams("industry_code", industry_code)
                .addParams("is_agreement", "1")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            showToast("注册成功");
                            finish();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(R.string.http_error);
                    }
                });
    }

    //检验手机号是否注册了三次
    private void checkPhone() {
        HttpRequest.postUrl(Api.PHONE_CHECK)
                .addParams("phone", idEdtPhone.getText().toString())
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            ForgetPassStp2Activity.actionStart(mAc, idEdtZh.getText().toString(), idEdtPhone.getText().toString(), idEdtPass1.getText().toString(), industry_code);
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
    }

    //检验帐号是否存在
    private void checkUserName() {
        HttpRequest.postUrl(Api.ACCOUNT_PASSWORD_CHECK)
                .addParams("UserName", userName)
                .addParams("type", "Register")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        ifCheck = Utils.checkCode(mAc, json);
                        if (ifCheck) {
                            checkPhone();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(e.getMessage());
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 601://行业
                    String stringExtra = data.getStringExtra(IndustryActivity.INDUSTRY_NAME);
                    idTvIndustry.setText(stringExtra);
                    idTvIndustry.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
                    industry_code = data.getStringExtra(IndustryActivity.INDUSTRY_CODE);
                    break;
            }
        }
    }
}
